import 'package:flutter/material.dart';

import 'package:tencent_cloud_chat_uikit/theme/color.dart';
import 'package:tencent_chat_i18n_tool/tencent_chat_i18n_tool.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/screen_utils.dart';

import 'package:provider/provider.dart';
import 'package:tencent_cloud_chat_demo/config.dart';
import 'package:tencent_cloud_chat_demo/src/provider/theme.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

class MobileScan extends StatefulWidget {
  const MobileScan({super.key});

  @override
  State<MobileScan> createState() => _MobileScanState();
}

class _MobileScanState extends State<MobileScan>
    with SingleTickerProviderStateMixin {
  final MobileScannerController controller = MobileScannerController();
  String? _scanResult;
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 4),
    )..repeat(reverse: true);
  }

  @override
  void dispose() {
    controller.dispose();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(
    BuildContext context,
  ) {
    final theme = Provider.of<DefaultThemeData>(context).theme;
    final isWideScreen =
        TUIKitScreenUtils.getFormFactor(context) == DeviceType.Desktop;
    return Scaffold(
      appBar: isWideScreen
          ? null
          : AppBar(
              iconTheme: const IconThemeData(
                color: Colors.white,
              ),
              shadowColor: theme.weakDividerColor,
              elevation: 1,
              title: Text(
                TIM_t("扫一扫"),
                style: const TextStyle(
                  fontSize: IMDemoConfig.appBarTitleFontSize,
                  color: Colors.white, // 设置字体颜色为白色
                ),
              ),
              flexibleSpace: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(colors: [
                    theme.lightPrimaryColor ?? CommonColor.lightPrimaryColor,
                    theme.primaryColor ?? CommonColor.primaryColor
                  ]),
                ),
              ),
            ),
      body: Stack(
        children: [
          Expanded(
            child: MobileScanner(
              controller: controller,
              onDetect: (capture) {
                final barcodes = capture.barcodes;
                if (barcodes.isNotEmpty) {
                  final String code = barcodes.first.rawValue ?? '无法识别';
                  setState(() => _scanResult = code);
                  _handleScanResult(code);
                }
              },
            ),
          ),
          // 添加扫描动画
          Positioned.fill(
            child: AnimatedBuilder(
              animation: _animationController,
              builder: (context, child) {
                return CustomPaint(
                  painter: _ScanLinePainter(
                    animationValue: _animationController.value,
                  ),
                );
              },
            ),
          ),
          // 显示扫描结果
          if (_scanResult != null)
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text('扫描结果: $_scanResult'),
            ),
        ],
      ),
    );
  }

  void _handleScanResult(String code) {
    // 这里处理扫描结果
    debugPrint('扫描到内容: $code');

    // 示例：显示简单对话框
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('扫描成功'),
        content: Text(code),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
}

// 自定义扫描线绘制器
class _ScanLinePainter extends CustomPainter {
  final double animationValue;

  _ScanLinePainter({required this.animationValue});

  @override
  void paint(Canvas canvas, Size size) {
    const lineHeight = 6.0; // 扫描线高度
    final lineWidth = size.width * 0.8; // 扫描线宽度为屏幕宽度的 80%
    final startX = (size.width - lineWidth) / 2; // 居中
    final lineY = size.height * animationValue; // 动态 Y 坐标

    final rect =
        Rect.fromLTWH(startX, lineY - lineHeight / 2, lineWidth, lineHeight);
    final rRect =
        RRect.fromRectAndRadius(rect, const Radius.circular(3.0)); // 圆角矩形

    final gradient = LinearGradient(
      colors: [
        Colors.green.withOpacity(0.0),
        Colors.green.withOpacity(0.8),
        Colors.green.withOpacity(0.0),
      ],
      stops: const [0.0, 0.5, 1.0],
    );

    final paint = Paint()
      ..shader = gradient.createShader(rect)
      ..style = PaintingStyle.fill;

    canvas.drawRRect(rRect, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
